package com.proxy.service.impl;

import cn.hutool.core.util.StrUtil;
import com.proxy.service.KeyFactory;

import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicReference;

import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;

/**
 * Key值获取实现类
 *
 * @author LiKun
 * @date 2021/9/15 14:09
 */
public class KeyFactoryService implements KeyFactory {
    private static final String SEPARATOR = "-";
    private static final String DEFAULT_RULE = "Key";
    private final AtomicReference<BigInteger> reference = new AtomicReference<>(ZERO);

    @Override
    public String getKey() {
        return this.getKey(DEFAULT_RULE);
    }

    @Override
    public String getKey(String rule) {
        this.increaseIndex();
        rule = StrUtil.isEmpty(rule) ? DEFAULT_RULE : rule;

        return rule + SEPARATOR + reference.get().toString();
    }

    /**
     * 将reference中的值加一
     */
    private void increaseIndex() {
        reference.compareAndSet(reference.get(), reference.get().add(ONE));
    }
}
